<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row>
          <div :class="advanced ? null: 'fold'">
            <a-col :span="8">
              <a-form-item
                label="流程名称"
                :labelCol="{span: 8}"
                :wrapperCol="{span: 10, offset: 2}">
                <a-input v-model="queryParams.name"/>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button @click="reset">重置</a-button>
            </a-col>
            <a-col :span="12" push="12">
              <a-button type="primary" @click="showFlowableModeler">设计新流程</a-button>
            </a-col>
          </div>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="operation" slot-scope="text, record">
          <a-space>
            <a-popover title="流程设计图" trigger="hover" placement="left" @visibleChange="(e) => showImage(e, record.id)">
              <flow-design-previewer slot="content" :recordId="record.id" :ref="'fdp-' + record.id"></flow-design-previewer>
              <a title="预览">预览</a>
            </a-popover>
            <a @click="config(record)" title="配置">配置</a>
            <a-popconfirm placement="topRight"
                          ok-text="发布"
                          cancel-text="取消"
                          @confirm="publish(record)"
                          title="确认发布新版本？">
              <a>发布</a>
            </a-popconfirm>
            <a-dropdown v-model="record.dropdownVisible">
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">更多
                <a-icon type="down"/>
              </a>
              <a-menu slot="overlay" @click="(e) => {if (e.key !== '3') record.dropdownVisible = false}">
                <a-menu-item key="1">
                  <a @click="suspend(record)">挂起</a>
                </a-menu-item>
                <a-menu-item key="2">
                  <a @click="active(record)">激活</a>
                </a-menu-item>
                <a-menu-item key="3">
                  <a-popconfirm placement="leftTop"
                                ok-text="取消"
                                cancel-text="删除"
                                @cancel="deleteModel(record)"
                                @visibleChange="(visible) => {if (!visible) record.dropdownVisible = false}"
                                title="删除流程定义不会破坏已有的流程数据，确认删除？">
                    <a-icon slot="icon" type="info-circle" style="color: red"/>
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item key="4">
                  <a>历史版本</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </a-space>
        </template>
      </a-table>
    </div>
    <ProcessDesigner ref="ProcessDesigner" @success="search" @close="search"></ProcessDesigner>
    <ProcessSuspendOrActive ref="ProcessSuspendOrActive" @success="search"></ProcessSuspendOrActive>
  </a-card>
</template>
<script>
import ProcessDesigner from './ProcessDesigner'
import ProcessSuspendOrActive from './ProcessSuspendOrActive'
import FlowDesignPreviewer from './FlowDesignPreviewer'

export default {
  name: 'ProcessDesignManage',
  components: {ProcessSuspendOrActive, ProcessDesigner, FlowDesignPreviewer},
  data () {
    return {
      // 数据初始区域
      advanced: false,
      queryParams: {},
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    columns () {
      return [
        {
          title: '流程定义KEY',
          dataIndex: 'definitionKey'
        }, {
          title: '流程名称',
          dataIndex: 'name'
        }, {
          title: '创建时间',
          dataIndex: 'created'
        }, {
          title: '更新时间',
          dataIndex: 'lastUpdated'
        }, {
          title: '最新发布版本',
          dataIndex: 'version',
          customRender: (version) => {
            return 'V' + version
          }
        }, {
          title: '最近发布时间',
          dataIndex: 'deployTime'
        }, {
          title: '草稿状态',
          dataIndex: 'draftStatus',
          customRender: (status) => {
            switch (status) {
              case '未发布':
                return <a-tag color="orange">未发布</a-tag>
              case '已发布':
                return <a-tag color="green">已发布</a-tag>
              default:
                return status
            }
          }
        }, {
          title: '发布状态',
          dataIndex: 'deployStatus',
          customRender: (status) => {
            switch (status) {
              case '活动中':
                return <a-tag color="green">活动中</a-tag>
              case '未发布':
                return <a-tag color="grey">未发布</a-tag>
              case '已挂起':
                return <a-tag color="red">已挂起</a-tag>
              default:
                return status
            }
          }
        },
        {
          title: '操作',
          width: 200,
          dataIndex: 'operation',
          scopedSlots: {customRender: 'operation'}
        }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    showImage (visible, id) {
      if (visible) {
        this.$nextTick(() => this.$refs['fdp-' + id].refresh())
      }
    },
    suspend (record) {
      this.$refs.ProcessSuspendOrActive.suspend(record)
    },
    active (record) {
      this.$refs.ProcessSuspendOrActive.active(record)
    },
    showFlowableModeler () {
      this.$refs.ProcessDesigner.newModel()
    },
    publish (record) {
      this.$post('process/design/deploy', {
        id: record.id
      }).then((res) => {
        if (res.data.status) {
          this.$message.success(res.data.message)
          this.search()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    deleteModel (record) {
      this.$delete('process/design/delete', {
        modelId: record.id
      }).then((res) => {
        if (res.data.status) {
          this.$message.success(res.data.message)
          this.search()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    config (record) {
      this.$refs.ProcessDesigner.editModel(record.id)
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...filteredInfo
      }, this.queryParams)
    },
    reset () {
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      }, this.queryParams)
    },
    fetch (params = {}, querypas) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('process/design/list', {
        ...params, ...querypas
      }).then((res) => {
        if (res.data.status) {
          let data = res.data.data
          const pagination = {...this.pagination}
          pagination.total = data.total
          this.dataSource = data.rows
          this.pagination = pagination
        } else {
          this.$message.error(res.data.message)
        }
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
